package com.wuseguang.springcloud.service.impl;

import com.wuseguang.springcloud.Classcardservice.ClassCardFieldService;
import com.wuseguang.springcloud.Classcardservice.ClassCardService;
import com.wuseguang.springcloud.dao.jdbc.BanCardJdbc;
import com.wuseguang.springcloud.entity.Holiday;
import com.wuseguang.springcloud.service.BanCardService;
import com.wuseguang.springcloud.util.CodeUtil;
import com.wuseguang.springcloud.util.DateUtil;
import com.wuseguang.springcloud.util.MyDES;
import com.wuseguang.springcloud.util.Result;
import net.dongliu.apk.parser.ApkFile;
import net.dongliu.apk.parser.bean.ApkMeta;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class BanCardServiceImpl implements BanCardService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ClassCardFieldService classCardFieldService;


    @Autowired
    private ClassCardService classCardService;

    @Autowired
    private BanCardJdbc banCardJdbc;
    //关机时间
    private static String gtime = "";
    //节假日配置时间
    private static String htime = "00:01:00";

    private String flag = "1";

    /**
     * @描述 组合查询设备详情
     * @创建人 zm
     * @创建时间 2019/12/27
     */
    @Override
    public List<Map<String, Object>> queryBanCardAll(String school_id, String gradeid, String classid, String state, String deviceid) {
        logger.info("school_id={},gradeid={},classid={},state={},deviceid={}", school_id, gradeid, classid, state, deviceid);
        String csql = " where 1=1 ";

        //按班级查询
        if (classid != null && !"".equals(classid) && !"0".equals(classid)) {
            csql += " and classid= " + classid;
        }

        //按在线/离线查询   连接断开5分钟视为离线  0是离线  1为在线
        if (state != null && !"".equals(state)) {
            csql += " and state= " + state;
        }

        //按年级查询
        if (gradeid != null && !"".equals(gradeid) && (classid == null || "".equals(classid))) {
            String sql1 = " SELECT GROUP_CONCAT(s.id) string FROM grade g, classes s WHERE g.id=s.grade_id " +
                    "   AND g.school_id= s.school_id AND s.school_id=? AND g.id=?";
            String s = banCardJdbc.queryString(sql1, school_id, gradeid);
            if (!"".equals(s)) {
                csql += " and classid in(" + s + ")";
            }
        }

        //根据设备id 模糊查询
        if (deviceid != null && !"".equals(deviceid)) {
            csql += " and deviceid like '%" + deviceid + "%'";
        }
        logger.info("csql={}", csql);
        String sql = "  SELECT*FROM ( SELECT p.name  deviceType,d.deviceType eDeviceType,d.id bancardid,c.id classroomid,c.name classroomname,c.remarks,c.classid,d.deviceid,d.version,d.heartbeattime,d.monday,d.tuesday,d.wednesday,d.thursday,d.friday,d.saturday,d.sunday,d.screenshot,d.screentime,b.classname,d.volume,  " +
                "(CASE WHEN d.heartbeattime >= NOW() - INTERVAL 5 MINUTE THEN 1 WHEN d.heartbeattime< NOW() - INTERVAL 5 MINUTE OR d.heartbeattime " +
                "IS NULL THEN 0 ELSE 0 END) state FROM bancard d LEFT JOIN devicetype p ON d.deviceType=p.device_type  LEFT JOIN classroom c ON d.classroomid=c.id " +
                "   LEFT JOIN (SELECT s.name classname,s.id FROM grade g, classes s WHERE g.id=s.grade_id " +
                "   AND g.school_id= s.school_id AND s.school_id=? ) b ON c.classid=b.id WHERE d.school_id=?) h  " + csql;
        logger.info("sql={}", sql);
        return banCardJdbc.getMapList(sql, school_id, school_id);
    }


    /**
     * @描述 设备一键关机或批量一键关机
     * @创建人 zm
     * @创建时间 2019/12/27
     */
    @Transactional
    @Override
    public int updateDeviceShutdown(String school_id, String deviceids) {
        logger.info("school_id={},deviceid={}", school_id, deviceids);
        String sql = "UPDATE bancard SET SHUTDOWN=1,updatetime=NOW() WHERE school_id=? and id in (" + deviceids + ")";
        return banCardJdbc.updateByParameter(sql, school_id);
    }

    /**
     * @描述 设备一键重启或批量一键重启
     * @创建人 zm
     * @创建时间 2019/12/27
     */
    @Transactional
    @Override
    public int updateDeviceRestartflag(String school_id, String deviceids) {
        logger.info("school_id={},deviceid={}", school_id, deviceids);
        String sql = "UPDATE bancard SET restartflag=1,updatetime=NOW() WHERE school_id=? and id in (" + deviceids + ")";
        return banCardJdbc.updateByParameter(sql, school_id);
    }

    /**
     * @描述 设备一键截屏或批量一键截屏
     * @创建人 zm
     * @创建时间 2019/12/27
     */
    @Transactional
    @Override
    public int updateDeviceScreenflag(String school_id, String deviceids) {
        logger.info("school_id={},deviceid={}", school_id, deviceids);
        String sql = "UPDATE bancard SET screenflag=1,updatetime=NOW() WHERE school_id=? and id in (" + deviceids + ")";
        return banCardJdbc.updateByParameter(sql, school_id);
    }

    /**
     * @描述 升级
     * @创建人 zm
     * @创建时间 2019/12/29
     */
    @Transactional
    @Override
    public int updateUpgradeflag(String school_id, String upgradeurl, String deviceids) {
        logger.info("school_id={},deviceid={}", school_id, deviceids);
        String sql = "UPDATE bancard SET upgradeurl=?,upgradeflag=1,updatetime=NOW() WHERE school_id=? and id in (" + deviceids + ")";
        return banCardJdbc.updateByParameter(sql, upgradeurl, school_id);
    }

    /**
     * @描述 重置密码
     * @创建人 zm
     * @创建时间 2019/12/27
     */
    @Transactional
    @Override
    public int updatepassword(String school_id, String password) {
        logger.info("school_id={}", school_id);
        String sql = "UPDATE school SET password=? WHERE id=? ";
        return banCardJdbc.updateByParameter(sql, MyDES.encryptBasedDes(password), school_id);
    }

    /**
     * @描述 声音控制
     * @创建人 zm
     * @创建时间 2019/12/27
     */
    @Transactional
    @Override
    public int updateVolume(String school_id, String deviceids, String volume) {
        logger.info("school_id={},deviceid={}", school_id, deviceids);
        String sql = "UPDATE bancard SET volume=?,volumeflag=1,updatetime=NOW() WHERE school_id=? and id in (" + deviceids + ")";
        return banCardJdbc.updateByParameter(sql, volume, school_id);
    }

    /**
     * @描述 删除设备，并删除相关节假日的信息
     * @创建人 zm
     * @创建时间 2019/12/27
     */
    @Override
    public int delDevice(String school_id, String deviceids) {
        String sql1 = "UPDATE bancard SET relieveflag=1 WHERE school_id=? and id in (" + deviceids + ")";
        banCardJdbc.updateByParameter(sql1, school_id);
        classCardService.bancardAndCards(deviceids);
        logger.info("school_id={},deviceid={}", school_id, deviceids);
        String sql = "DELETE  FROM  bancard WHERE school_id=? and id in (" + deviceids + ")";
        sql1 = "DELETE  FROM holiday_deviceid WHERE  device_id in (" + deviceids + ")";
        banCardJdbc.updateByParameter(sql1);
        return banCardJdbc.updateByParameter(sql, school_id);
    }

    /**
     * @描述 查询所有设备类型
     * @创建人 zm
     * @创建时间 2019/12/27
     */
    @Override
    public List<Map<String, Object>> queryDeviceType() {
        String sql = " SELECT id,device_type deviceType,name FROM devicetype";
        return banCardJdbc.queryListMap(sql);
    }

    /**
     * @描述 查询所有教室
     * @创建人 zm
     * @创建时间 2019/12/27
     */
    @Override
    public List<Map<String, Object>> queryClassRoomAll(String school_id) {
        String sql = " SELECT c.id,CONCAT(c.name,IF(c.classid IS NULL,'',CONCAT('(',s.name,')'))) name,IF(c.classid IS NULL,1,0) state FROM classroom c LEFT JOIN classes s  ON c.classid=s.id WHERE c.school_id=?";
        return banCardJdbc.queryListMap(sql, school_id);
    }

    /**
     * @描述 查询该设备所有节假日时间
     * @创建人 zm
     * @创建时间 2019/12/27
     */
    @Override
    public List<Map<String, Object>> queryHolidayAll(String bancardid) {
        String sql = "SELECT h.name,h.id,d.holiday_st,d.holiday_et,d.state,d.opertime FROM holiday h LEFT JOIN " +
                " holiday_deviceid d ON h.id=d.holiday_id AND d.device_id=? ORDER BY h.id";
        return banCardJdbc.getMapList2(sql, bancardid);
    }

    /**
     * @描述 查询该设备使用的节假日时间
     * @创建人 zm
     * @创建时间 2019/12/27
     */
    @Override
    public List<Map<String, Object>> queryHolidayAllUse(String bancardid) {
        String sql = "SELECT h.name,h.id,d.holiday_st,d.holiday_et,d.state,d.opertime FROM holiday h,holiday_deviceid d where h.id=d.holiday_id AND d.device_id=? and d.state=1 ORDER BY h.id";
        return banCardJdbc.getMapList2(sql, bancardid);
    }

    /**
     * @描述 修改班牌日常时间
     * @创建人 zm
     * @创建时间 2019/12/27
     */
    @Transactional
    @Override
    public int updateBancardTime(String ids, String monday, String tuesday, String wednesday, String thursday, String friday, String saturday, String sunday) {
        logger.info("ids={},BancardTime={}", ids, monday, tuesday, wednesday, thursday, friday, saturday, sunday);
        String sql = "UPDATE bancard SET monday=?,tuesday=?,wednesday=?,thursday=?,friday=?,saturday=?,sunday=?,holidayheartbeat=1 WHERE id IN (" + ids + ")";
        int i = banCardJdbc.updateByParameter(sql, monday, tuesday, wednesday, thursday, friday, saturday, sunday);
        return i;
    }

    /**
     * @描述 批量修改节假日
     * @创建人 zm
     * @创建时间 2019/12/27
     */
    @Override
    public int batchAddHoliday(String s, String[] ids, List<Holiday> holidayList) {
        int i = banCardJdbc.batchUpdateDepartMent(ids, holidayList);
        if (i > 0) {
            classCardFieldService.pushClassCard(s, "holidayheartbeat", flag);
        }
        return i;
    }


    /**
     * @描述 修改设备类型和绑定的教室
     * @创建人 zm
     * @创建时间 2019/12/27
     */
    @Override
    public int updateDevicTypeorclassroom(String id, String deviceType, String classroomid, String deviceid) {
        logger.info("id={},deviceType={},classroomid={}", id, deviceType, classroomid);
        String sql = "SELECT classroomid,deviceType FROM bancard WHERE id=?";
        Map<String, Object> map = banCardJdbc.queryMap(sql, id);
        sql = "UPDATE bancard SET deviceType=?,classroomid=?,deviceid=?,updatetime=NOW() WHERE id=?";
        int i = banCardJdbc.updateByParameter(sql, deviceType, classroomid, deviceid, id);
        if (i > 0) {
            int devicetypeflag = 0;
            int classflag = 0;
            if (!deviceType.equals(map.get("deviceType").toString())) {//用户是修改了班级信息还是设备类型需要判断，结合判断结果，对班牌进行个推推送。
                devicetypeflag = 1;
            }
            if (!classroomid.equals(map.get("classroomid").toString())) {
                classflag = 1;
            }
            sql = "UPDATE bancard SET classflag=?,devicetypeflag=? WHERE id=?";
            banCardJdbc.updateByParameter(sql, classflag, devicetypeflag, id);
        }
        return i;
    }

    /**
     * @描述 批量修改设备类型
     * @创建人 zm
     * @创建时间 2019/12/27
     */
    @Transactional
    @Override
    public int batchupdateDevicType(String ids, String deviceType) {
        logger.info("id={},deviceType={}", ids, deviceType);
        String sql = "UPDATE bancard SET deviceType=?,updatetime=NOW(),devicetypeflag=1 WHERE id in (" + ids + ")";
        int i = banCardJdbc.updateByParameter(sql, deviceType);
        return i;
    }

    /**
     * @描述 绑定设备
     * @创建人 zm
     * @创建时间 2019/12/28
     */
    @Override
    public Result addDevicTypeorclassroom(String school_id, String deviceid, String deviceType, String classroomid) {
        logger.info("deviceid={},deviceType={},classroomid={}", deviceid, deviceType, classroomid);
        String sql1 = "SELECT sbnumber count FROM school WHERE id=?";
        String sql2 = "SELECT COUNT(*) count FROM bancard WHERE school_id=?";
        //查询该学校最大设备数量
        Integer integer = banCardJdbc.queryCount(sql1, school_id);
        Integer integer2 = banCardJdbc.queryCount(sql2, school_id);
        if (integer2 >= integer) {
            return new Result(CodeUtil.BINDING_EXCEEDS);
        }
        String sql3 = "SELECT COUNT(*) count FROM bancard WHERE deviceid=? ";
        Integer integer3 = banCardJdbc.queryCount(sql3, deviceid);
        if (integer3 > 0) {
            return new Result(CodeUtil.BEEN_BOUND);
        }
        //添加设备
        String sql = "INSERT INTO bancard(deviceid,classroomid,deviceType,school_id) VALUES(?,?,?,?)";
        int i = banCardJdbc.updateByParameter(sql, deviceid, classroomid, deviceType, school_id);
        if (i > 0) {
            return new Result(CodeUtil.SUCCESS);
        }
        return new Result(CodeUtil.ADD_FAILURE);
    }

    @Override
    public int queryCount(String deviceid, String id) {
        //已被绑定
        String sql3 = "SELECT COUNT(*) count FROM bancard WHERE deviceid=? AND id!=?";
        Integer integer3 = banCardJdbc.queryCount(sql3, deviceid, id);
        return integer3;
    }

    /**
     * @描述 根据班级id查设备id
     * @创建人 zm
     * @创建时间 2020/2/28
     */
    @Override
    public Map<String, Object> queryDanCardIds(String classids) {
        logger.info("classids={}", classids);
        String sql = " SELECT GROUP_CONCAT(d.id) bancardids FROM classroom m,classes s,bancard d WHERE m.id=d.classroomid AND s.id=m.classid AND s.id in (" + classids + ")";
        Map<String, Object> map = new HashMap<>();
        try {
            map = banCardJdbc.queryMap(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (map == null || map.size() <= 0) {
            map.put("bancardids", "0");
            return map;
        }
        return map;
    }

    /**
     * @描述 查詢所有包含設備的班級
     * @创建人 zm
     * @创建时间 2020/3/10
     */
    @Override
    public Result queryEquipmentClassesAll(String schoolId) {
        try {
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            String sql = "select id,name from `grade` where `school_id`  = ?";
            logger.info("查询年级sql = {}", sql);
            List<Map<String, Object>> gradeList = banCardJdbc.queryListMap(sql, Integer.parseInt(schoolId));
            for (Map<String, Object> gradeMap : gradeList) {
                logger.info("年级信息 map = {}", gradeMap.toString());
                sql = "SELECT c.id,c.name  name  FROM classes c , classroom m , bancard b WHERE c.grade_id =? AND m.classid=c.id AND m.id=b.classroomid GROUP BY c.id ";
                logger.info("查询班级信息 sql = {}", sql);
                List<Map<String, Object>> classList = banCardJdbc.queryListMap(sql, gradeMap.get("id"));
                if (classList != null && classList.size() > 0) {
                    gradeMap.put("list", classList);
                    list.add(gradeMap);
                }
            }
            return new Result(list);
        } catch (Exception e) {
            logger.info("queryEquipmentClassesAll-->error={}", e);
        }
        return new Result();
    }

    @Override
    public Result getVersionNumber(MultipartFile file, String bancardids) {
  /*      try {
            String filePath = "/mnt";
            if (!file.isEmpty()) {
                String fileName = file.getOriginalFilename();
                String suffixName = fileName.substring(fileName.lastIndexOf("."));
                if (".apk".equals(suffixName)) {
                    filePath += "/apk/";
                }
                String uuidName = UUID.randomUUID().toString() + suffixName;
                filePath = filePath + uuidName;
            }

            System.out.println(filePath);
            File dest = new File(filePath);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            //写入
            file.transferTo(dest);

            //获取版本号
            ApkFile apkFile = new ApkFile(dest);
            ApkMeta apkMeta = apkFile.getApkMeta();
            Map<String, Object> map = new HashMap<>();
            String versionName = apkMeta.getVersionName();
            map.put("version", versionName);
            String sql = "UPDATE FROM bancard set version=? WHERE id (" + bancardids + ")";
            logger.info("getVersionNumber,sql={}", sql);
            banCardJdbc.updateByParameter(sql, versionName);
            //强制删除apk
            boolean result = false;
            int tryCount = 0;
            while (!result && tryCount++ < 10) {
                logger.info("回收次数，tryCount={}", tryCount);
                System.gc();
                result = dest.delete();
            }
            return new Result(map);
        } catch (IOException e) {
            logger.info("获取版本号异常，erorr={}", e);
        }*/
        return new Result();
    }
}
